<?php

class Sgit_Util_Array
{

    
    
    
    static function collectionCol($rows,$col=null)
    {
        $col=is_null($col) ? 'id' : $col;
        $ids=array();
        $rows=Sgit_Util_Object::toArray($rows);
        foreach($rows as $v)
            $ids[] = $v->$col;
          
        return $ids;
    }
    
    static function collectionKey($rows)
    {
        return array_keys($rows);
    }
    
    
    
    static function assocBy($rows, $key = 'id', $values = null)
    {
      
        if(empty($rows)) return '';
        $rows=Sgit_Util_Object::toArray($rows);
        
        foreach ((array )$rows as $v)
        {
           $salida[$v[$key]][]=self::iterateRow($v,$values);
        }

        return $salida;
    }


    static function assocSimpleBy($rows, $key = 'id', $values = null)
    {
        foreach ((array )$rows as $v)
        {
           if(isset($salida[$v[$key]]))
           {
            throw new Zend_Db_Table_Exception('Clave Duplicada, use Sgit_Util_ArrayAssocBy');
           }
           
           $salida[$v[$key]]=self::iterateRow($v,$values);
        }

        return $salida;
    }



    protected function iterateRow($row,$values)
    {
        if(is_array($values))
        {
            foreach($values as $k=>$v){
               $sal[$v]=$row[$v];
            }
            return $sal;
        }elseif(!is_null($values)){
            return $row[$values];
        }else{
            return $row;
        }
        
    }
    
    
    static function order($data, $field,$inverse = false)
    {
        if (!is_array($field))
            $field = array($field);
            
        

        uasort($data, 
            function ($a, $b)use ($field)
            {
                $retval = 0; 
                foreach ($field as $fieldname)
                {
                    if ($retval == 0)
                        $retval = strnatcmp($a[$fieldname], $b[$fieldname]) ; 
                }
                return $retval; 
            }
        );
        
        if($inverse)
            $data=array_reverse($data);
            
        return $data;
    }

    
    
    
    
    
    
}



    


